﻿using AcexeService.Models;
using AcexeService.ServiceModel.Basic;
using ServiceStack;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Linq;

//https://github.com/ServiceStack/ServiceStack.OrmLite
namespace AcexeService.ServiceInterface
{
    [Authenticate]
    public class BscJobServices : Service
    {
        /// <summary>
        /// 通过岗位ID(JobId)取岗位实体数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetJobName request)
        {
            var list = Db.Select<BSC_JOBNAME>(c => c.JOBID == request.JobId);
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }

        /// <summary>
        /// 编辑 岗位对应部门时 用到
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetJobNameWithOrg request)
        {
            var sqlexp = Db.From<BSC_JOBNAME>().Where(c => c.JOBID == request.JobId);
            sqlexp.Select<BSC_JOBNAME>(x => new { x.JOBID, x.JOBNO, x.JOBNAME });

            var list = Db.Select<Dictionary<string, object>>(sqlexp);
            if (list.Count > 0)
            {
                var q = Db.From<BSC_ORG_JOB>()
                    .Where(c => c.JOBID == request.JobId);
                var listid = Db.Select<BSC_ORG_JOB>(q);
                var ids = "";
                for (int i = 0; i < listid.Count; i++)
                {
                    ids += listid[i].ORGID + (i == listid.Count - 1 ? "" : ",");
                }
                list[0].Add("ORGID", ids);
                return list[0];
            }
            return null;
        }

        /// <summary>
        /// 查询岗位数据（分页、导出）
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(GetJobNameList request)
        {

            var miniuigridmodel = new MiniUiGridModel<BSC_JOBNAME>();
            var model = request.BscEmpModel;

            var q = Db.From<BSC_JOBNAME>();

            q.And(x => x.ISDELETED == model.ISDELETED);

            if (!string.IsNullOrEmpty(request.FuzzyJobNameName))
                q.And(p => p.JOBNAME.Contains(request.FuzzyJobNameName));

            miniuigridmodel.total = Db.Scalar<int>(q.Select(Sql.Count("*")));

            if (!request.Page.IsGetWholeData)
            {
                q.Take(request.Page.PageSize);
                q.Skip(request.Page.PageSize * request.Page.PageIndex);
            }

            if (!string.IsNullOrEmpty(request.Page.SortField))
            {
                if (request.Page.SortOrder == "asc")
                    q.OrderByFields(request.Page.SortField);
                else
                    q.OrderByFieldsDescending(request.Page.SortField);
            }
            else
            {
                q.OrderBy(x => x.ORDERNUM);
            }

            miniuigridmodel.data = Db.Select<BSC_JOBNAME>(q.Select(c => c));

            return miniuigridmodel;

        }

        /// <summary>
        /// 新增岗位
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(AddJobName request)
        {
            var dto = new MessageDto();
            var model = request.BscEmpModel;

            if (string.IsNullOrEmpty(model.JOBID))
            {
                dto.Flag = false;
                dto.Msg = "岗位ID不允许为空";
                return dto;
            }
            if (string.Equals(model.JOBNO, ""))
            {
                dto.Flag = false;
                dto.Msg = "岗位编号不允许为空";
                return dto;
            }
            // 字段值为null时不会更新数据，但是为""会更新为""
            if (string.Equals(model.JOBNAME, ""))
            {
                dto.Flag = false;
                dto.Msg = "岗位姓名不允许为空";
                return dto;
            }

            try
            {
                Db.Insert<BSC_JOBNAME>(model);
                dto.Flag = true;
                dto.Msg = "新增成功";
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 编辑岗位
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(EditJobName request)
        {
            var dto = new MessageDto();
            var model = request.BscEmpModel;

            if (string.IsNullOrEmpty(model.JOBID))
            {
                dto.Flag = false;
                dto.Msg = "岗位ID不允许为空";
                return dto;
            }
            if (string.Equals(model.JOBNO, ""))
            {
                dto.Flag = false;
                dto.Msg = "岗位编号不允许为空";
                return dto;
            }
            // 字段值为null时不会更新数据，但是为""会更新为""
            if (string.Equals(model.JOBNAME, ""))
            {
                dto.Flag = false;
                dto.Msg = "岗位姓名不允许为空";
                return dto;
            }

            try
            {
                var list = Db.Select<BSC_JOBNAME>(c => c.JOBID == model.JOBID);
                if (list.Count == 0)
                {
                    dto.Flag = false;
                    dto.Msg = "您编辑的岗位不存在，请刷新页面后重试";
                    return dto;
                }

                var editmodel = list[0];

                editmodel = AcexeService.ServiceInterface.Lib.AutoTransfer.GetModel<BSC_JOBNAME>(editmodel, model);
                Db.Update<BSC_JOBNAME>(editmodel);

                dto.Flag = true;
                dto.Msg = "修改成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }

        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(DeleteJobName request)
        {
            var dto = new MessageDto();

            if (request.JobId.Equals(string.Empty))
            {
                dto.Flag = false;
                dto.Msg = "空记录";
                return dto;
            }

            try
            {
                //只作虚删除
                Db.Update<BSC_JOBNAME>(new { ISDELETED = true, UPDATEON = DateTime.Now, UPDATEBY = request.DeleteBy }, p => p.JOBID == request.JobId);

                dto.Flag = true;
                dto.Msg = "注销成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }

        #region 处理岗位与组织部门的对应关系
        public object Any(GetJobByOrgId request)
        {
            string orgid = request.OrgId;
            if (string.IsNullOrEmpty(orgid))
            {
                return new List<StrObjDict>();
            }

            var q = Db.From<BSC_ORG_JOB>()
                .Join<BSC_JOBNAME>((a, b) => a.JOBID == b.JOBID && b.ISDELETED == false)
                .Join<ORG_ORGANIZATION>((a, b) => a.ORGID == b.ORGID && b.ISDELETED == false)
                .Where(c => c.ORGID == orgid)
                .OrderBy<BSC_JOBNAME>(c => c.ORDERNUM)
                .Select<BSC_ORG_JOB, BSC_JOBNAME, ORG_ORGANIZATION>((a, b, c) => new
                {
                    c.ORGNO,
                    c.ORGNAME,
                    b.JOBNAME,
                    b.JOBNO
                });

            var list = Db.Select<Dictionary<string, object>>(q);
            return list;
        }
        public object Any(GetOrganizationByJobId request)
        {
            string jobid = request.JobId;
            if (string.IsNullOrEmpty(jobid))
            {
                return new List<StrObjDict>();
            }

            var q = Db.From<BSC_ORG_JOB>()
                .Join<BSC_JOBNAME>((a, b) => a.JOBID == b.JOBID && b.ISDELETED == false)
                .Join<ORG_ORGANIZATION>((a, b) => a.ORGID == b.ORGID && b.ISDELETED == false)
                .Where(c => c.JOBID == jobid)
                .OrderBy<ORG_ORGANIZATION>(c => c.ORDERNUM)
                .Select<BSC_ORG_JOB, BSC_JOBNAME, ORG_ORGANIZATION>((a, b, c) => new
                {
                    c.ORGNO,
                    c.ORGNAME,
                    b.JOBNAME,
                    b.JOBNO
                });

            var list = Db.Select<Dictionary<string, object>>(q);
            return list;
        }
        public object Any(AddPairOrgJob request)
        {
            MessageDto dto = new MessageDto() { Msg = "" };
            if (string.IsNullOrEmpty(request.BscOrgJobModel.JOBID) || string.IsNullOrEmpty(request.BscOrgJobModel.ORGID))
            {
                dto.Msg = "必要参数JobId，OrgId不能为空";
                dto.Flag = false;
                return dto;
            }

            Db.Delete<BSC_ORG_JOB>(request.BscOrgJobModel);
            Db.Insert<BSC_ORG_JOB>(request.BscOrgJobModel);

            dto.Msg = "操作成功";
            dto.Flag = true;
            return dto;
        }

        public object Any(AddListPairOrgJob request)
        {
            MessageDto dto = new MessageDto() { Msg = "" };
            if (request.ListBscOrgJob.Count == 0)
            {
                dto.Msg = "参数数据行数为0";
                dto.Flag = false;
                return dto;
            }

            using (System.Data.IDbTransaction dbTrans = Db.OpenTransaction())
            {
                Db.Delete<BSC_ORG_JOB>(p => p.JOBID == request.ListBscOrgJob[0].JOBID);
                for (int i = 0; i < request.ListBscOrgJob.Count; i++)
                {
                    var model = request.ListBscOrgJob[i];
                    if (string.IsNullOrEmpty(model.JOBID) || string.IsNullOrEmpty(model.ORGID))
                    {
                        continue;
                    }
                    Db.Insert<BSC_ORG_JOB>(model);
                }

                dbTrans.Commit();
            }

            dto.Msg = "操作成功";
            dto.Flag = true;
            return dto;
        }
        public object Any(DeletePairOrgJob request)
        {
            MessageDto dto = new MessageDto() { Msg = "" };
            if (string.IsNullOrEmpty(request.BscOrgJobModel.JOBID) || string.IsNullOrEmpty(request.BscOrgJobModel.ORGID))
            {
                dto.Msg = "必要参数JobId，OrgId不能为空";
                dto.Flag = false;
                return dto;
            }

            Db.Delete<BSC_ORG_JOB>(request.BscOrgJobModel);
            dto.Msg = "删除成功";
            dto.Flag = true;
            return dto;
        }
        #endregion

    }

}